import axios from 'axios'
import { ElMessage } from 'element-plus'
import useStore from '@/store'
import { removeStore, getStore } from '@/utils/utils'
import i18n from '@/i18n.js'
const { t } = i18n.global
import router from '@/router'
// 请求超时 TODO 性能优化后 修改至 30000
axios.defaults.timeout = 600000
//axios.defaults.withCredentials=true;
// 添加一个请求拦截器
axios.interceptors.request.use(
  async (res) => {
    // res.baseURL = baseUrl || '',
    res.params = res.params || {}
    if (res.headers['Content-Type'] == 'application/json' && res.method == 'post') {
      res.params = res.data || {}
    } else {
      res.params = res.params || {}
    }
    res.headers.language = getStore('language')
    // res.headers.XIP = Object.values(await window.api.getMac()).map((info) => info.ipv4).join(', ')
    // res.headers.XIP = '1.208.112.154'
    if (getStore('Authorization') && JSON.parse(getStore('Authorization')).value != 'null') {
      res.headers.Authorization = JSON.parse(getStore('Authorization')).value
    }
    return res
  },
  (err) => {
    return Promise.reject(err)
  }
)

// 添加一个响应拦截器
axios.interceptors.response.use(
  (res) => {
    //loading.close()
    if (res.data.code) {
      if (res.data.code == 0) {
        return res.data
      } else if (res.data.code == 10000) {
        const { userStore } = useStore()
        ElMessage({
          message: t('Popcorn.LoginHasExpired'),
          type: 'warning'
        })
        setTimeout(() => {
          userStore.setLoginStatus(false)
          removeStore('loginStatus')
          removeStore('userInfo')
          userStore.setToken(`{"value":"null"}`)
         // window.location.href = '/home'
          router.push("/home").then(() => {
            // 导航完成后刷新页面
            window.location.reload();
          });
        }, 2000)
        return
      } 
      else {
        return res.data
      }
    } else {
      if(res.data.code == 10000){
        const { userStore } = useStore()
        ElMessage({
          message: t('Popcorn.LoginHasExpired'),
          type: 'warning'
        })
        setTimeout(() => {
          userStore.setLoginStatus(false)
          removeStore('loginStatus')
          removeStore('userInfo')
          userStore.setToken(`{"value":"null"}`)
          // window.location.href = '/home'
          router.push("/home").then(() => {
            // 导航完成后刷新页面
            window.location.reload();
          });
        }, 2000)
      }
      return res.data
    }
  },
  (error) => {
    if (String(error).indexOf('timeout') > -1) {
      ElMessage({
        message: t('textError.RequestTimeout'),
        type: 'error'
      })
      return
    } else if (String(error).indexOf('Network Error') > -1) {
      ElMessage({
        message: t('textError.NetworkError'),                          
        type: 'error'
      })
    } else {
      ElMessage({
        message: t('textError.ServiceError'),
        type: 'error'
      })
    }
  }
)

export const postHeaderJson = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, {
        headers: {
          'Content-Type': 'application/json'
        },
        emulateJSON: true
      })
      .then(
        (res) => {
          resolve(res)
        },
        (err) => {
          reject(err)
        }
      )
  })
}
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 *
 */
export const get = (url, params, obj = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .get(
        url,
        {
          params: params
        },
        obj
      )
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export const post = (url, params, obj = {}) => {
  //以x-www-form-urlencoded 格式post数据的时候，需要使用qs.stringify()
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, obj)
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export const postFile = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, {
        headers: {
          'Content-Type': 'multipart/form-data;charset=utf-8'
        }
      })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
/**
 * postForm
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export const postForm = (url, params) => {
  //以x-www-form-urlencoded 格式post数据的时候，需要使用qs.stringify()
  return new Promise((resolve, reject) => {
    axios({
      url: url,
      method: 'post',
      data: params,
      transformRequest: [
        function (data) {
          // Do whatever you want to transform the data
          let ret = ''
          for (let it in data) {
            const value = data[it] !== undefined ? data[it] : ''
            ret += `&${encodeURIComponent(it)}=${encodeURIComponent(value)}`
          }
          return ret.slice(1)
        }
      ],
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
        //   'Content-Type': 'multipart/form-data'
      }
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
/**
 * put 对应put请求
 * @param {String} url
 * @param {Object} data
 */
export const put = (url, params, obj = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .put(url, params, {
        headers: {
          'Content-Type': 'application/json'
        },
        ...obj
      })
      .then(
        (response) => {
          resolve(response)
        },
        (err) => {
          reject(err)
        }
      )
  })
}
/**
 * delete方法，delete请求
 * @param {String} url
 * @param {Object} params
 */

export const delet = (url, params = {}) => {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, {
        params: params
      })
      .then((response) => {
        resolve(response)
      })
      .catch((err) => {
        reject(err)
      })
  })
}
